package com.wish.wishsystem_management.task;

import com.google.gson.Gson;
import com.wish.wishsystem_management.api.HttpContextUtils;
import com.wish.wishsystem_management.api.IPUtils;
import com.wish.wishsystem_management.api.SysLog;
import com.wish.wishsystem_management.service.ISysLogService;
import dto.systemDto.SysLogDto;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 系统日志，切面处理类
 */
@Aspect
@Component
public class SysLogAspect {
	@Autowired
	private ISysLogService sysLogService;

	@Pointcut("@annotation(com.wish.wishsystem_management.api.SysLog)")
	public void logPointCut() {

	}
	//环绕通知
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;


		System.err.println(time);


		//保存日志
		saveSysLog(point, time);

		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
		System.err.println(time);
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		SysLogDto sysLogDto = new SysLogDto();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			sysLogDto.setOperation(syslog.value());
		}

		//请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLogDto.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		try{
			String params = new Gson().toJson(args[0]);
			sysLogDto.setParams(params);
		}catch (Exception e){

		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		sysLogDto.setIp(IPUtils.getIpAddr(request));

		//用户名
//		String username = ((SysUserDto) SecurityUtils.getSubject().getPrincipal()).getUsername();
//		sysLogDto.setUsername(username);

		sysLogDto.setTime(time);
		sysLogDto.setCreateDate(new Date());
		//保存系统日志
		sysLogService.save(sysLogDto);
	}

}
